﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OneStationFile.WEB.App_Start
{
    
    public class UserLoginState : ActionFilterAttribute
    {
        //private Model.Users _users = (Model.Users)Common.CacheHelper.GetCache("users");
        public override void OnActionExecuting(ActionExecutingContext actionExecutedContext)
        {
            Model.Users users = (Model.Users)Common.CacheHelper.GetCache("users");
            try
            {
                base.OnActionExecuting(actionExecutedContext);
                //Core.Common.MemcachedCachePolicy cm = new Core.Common.MemcachedCachePolicy();
                //string sid = actionExecutedContext.HttpContext.Session.SessionID;
                //string Sid = "fwadmin_" + sid;
                if (users == null)
                {
                    string url = actionExecutedContext.HttpContext.Request.Path;
                    actionExecutedContext.Controller.ViewBag.Error = "您的登录已超时，请重新登录";
                    actionExecutedContext.HttpContext.Response.Redirect("/Login/LoginIn?url=" + url);
                    actionExecutedContext.Result = new HttpNotFoundResult();


                }
                else
                {
                    //Core.Model.Users mu = (Core.Model.Users)cm.Get(Sid);
                    var controllerName = actionExecutedContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                    var actionName = actionExecutedContext.ActionDescriptor.ActionName;
                    if (users.Account != "admin")
                    {
                        List<Model.Node> nodes = users.Role.Nodes.ToList();
                        if (nodes.Where(p=>p.Controller == controllerName && p.Action == actionName).Count()<=0)
                        {
                            if (actionExecutedContext.HttpContext.Request.IsAjaxRequest())
                            {
                                actionExecutedContext.HttpContext.Response.Redirect("/Error/AjaxError");
                                actionExecutedContext.Result = new HttpNotFoundResult();
                            }
                            else
                            {
                                actionExecutedContext.HttpContext.Response.Redirect("/Error/PageError");
                                actionExecutedContext.Result = new HttpNotFoundResult();
                            }
                        }

                    }

                }

            }
            catch (System.Exception)
            {

            }

        }
    }
}